package com.sjgs.gis.service;

import com.sjgs.gis.domain.Chunk;
import com.sjgs.gis.repository.ChunkRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Service
public class ChunkService {

    private final ChunkRepository repository;


    public ChunkService(ChunkRepository repository) {
        this.repository = repository;
    }

    public Flux<Chunk> findAll() {
        return repository.findAll();
    }

    public Flux<Chunk> findAllByFkeyAndStatus(String fkey, Integer status) {
        return repository.findAllByFkeyAndStatus(fkey, status);
    }

    public Flux<Chunk> findAllByFkeyAndStatusAndChunkAddrIsNot(String fkey, Integer status, String chunkAddr) {
        return repository.findAllByFkeyAndStatusAndChunkAddrIsNot(fkey, status, chunkAddr);
    }

    public Mono<Chunk> findByFkeyAndIndexAndHashAndStatus(String fkey, Long index, String hash, Integer status) {
        return repository.findByFkeyAndIndexAndHashAndStatus(fkey, index, hash, status);
    }

    public Mono<Long> countByFkeyAndStatus(String fkey, Integer status) {
        return repository.countByFkeyAndStatus(fkey, status);
    }

    public Mono<Chunk> save(Chunk chunk) {
        return repository.save(chunk);
    }


    public Mono<Void> delete(Chunk chunk) {
        return repository.delete(chunk);
    }

    public Mono<Void> deleteAllByFkey(String fkey) {
        return repository.deleteAllByFkey(fkey);
    }

    @Transactional
    public Mono<Chunk> insertOrUpdate(Chunk chunk) {
        return repository.findAllByFkeyAndIndex(chunk.getFkey(), chunk.getIndex())
                .collectList()
                .flatMap(list -> {
                    if (list.size() > 0) {
                        Chunk chk = list.get(0);
                        chunk.setId(chk.getId());
                        return save(chunk);
                    } else {
                        return save(chunk);
                    }
                });
    }

    public Flux<Chunk> findAllByFkeyAndStatusAndStartAndAndEnd(String fkey, Integer status, Long start, Long end) {
        return repository.findAllByFkeyAndStatusAndStartAndAndEnd(fkey, status, start, end);
    }
}
